package com.gkj.controller;


import com.github.pagehelper.PageInfo;
import com.gkj.blog.business.dto.PageResult;
import com.gkj.blog.business.enums.ResponseStatus;
import com.gkj.blog.business.service.RoleResourcesService;
import com.gkj.blog.business.service.RoleService;
import com.gkj.blog.business.vo.condition.RoleConditionVO;
import com.gkj.blog.business.vo.entity.Role;
import com.gkj.blog.framework.object.ResponseVO;
import com.gkj.blog.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/roles")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleResourcesService roleResourcesService;

    @RequestMapping("/list")
    public PageResult list(RoleConditionVO vo) {
        PageInfo<Role> pageInfo = roleService.findPageBreakByCondition(vo);
        return ResultUtil.tablePage(pageInfo);
    }
    @RequestMapping("/listAll")
    public ResponseVO listAll(){
        RoleConditionVO vo=new RoleConditionVO();
        vo.setPageSize(200);
        PageInfo<Role> pageInfo = roleService.findPageBreakByCondition(vo);
        return ResultUtil.success(null,pageInfo==null?null:pageInfo.getList());
    }
    @PostMapping("/rolesWithSelected")
    public ResponseVO<List<Role>> rolesWithSelected(Integer uid) {
        return ResultUtil.success(null, roleService.queryRoleListWithSelected(uid));
    }

    //分配角色
    @PostMapping("/saveRoleResources")
    public ResponseVO saveRoleResources(Long roleId, @RequestParam("resourcesIds[]") Long[] resourcesIds) {
        if (StringUtils.isEmpty(roleId)) {
            return ResultUtil.error("error");
        }
        roleResourcesService.addRoleResources(roleId, resourcesIds);
        return ResultUtil.success("成功");
    }

    @PostMapping(value = "/add")
    public ResponseVO add(Role role) {
        roleService.insert(role);
        return ResultUtil.success("成功");
    }

    @PostMapping(value = "/remove")
    public ResponseVO remove(@RequestParam("ids[]") Long[] ids) {
        if (!roleService.removeRoleAndRelation(ids)) {
            return ResultUtil.error(500, "请至少选择一条记录");
        }
        return ResultUtil.success("成功删除 [" + ids.length + "] 个角色");
    }

    @PostMapping("/get/{id}")
    public ResponseVO get(@PathVariable Long id) {
        return ResultUtil.success(null, this.roleService.select(id));
    }

    @PostMapping("/edit")
    public ResponseVO edit(Role role) {
        try {
            roleService.update(role);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("角色修改失败！");
        }
        return ResultUtil.success(ResponseStatus.SUCCESS);
    }

}
